home *** CD-ROM | disk | FTP | other *** search
- Path: prairie.nodak.edu!not-for-mail
- From: wstark@prairie.nodak.edu (Just Me)
- Newsgroups: comp.lang.c
- Subject: Re: why get 9 strings only?
- Date: 31 Jan 1996 05:56:48 -0600
- Organization: North Dakota Higher Education Computing Network (NDHECN)
- Message-ID: <4enle0$hfs@prairie.nodak.edu>
- References: <4e51th$4bi@news.nevada.edu> <310909EC.782B007C@eiffel.com>
- NNTP-Posting-Host: prairie.nodak.edu
- Mime-Version: 1.0
- Content-Type: text/plain; charset=US-ASCII
- Content-Transfer-Encoding: 7bit
-
- In article <310909EC.782B007C@eiffel.com>,
- Guus Leeuw jr. <guusl@eiffel.com> wrote:
-
- I realize that this is just a simple program, but there are some concepts
- that should be pointed out, anyway.
-
- >int
- >main ()
- >{
- > char str[10][80];
- > char dummy[2]; /* *** new new new *** */
-
- why make it just 2? are you sure that's big enough? (see below)
-
- > int i, j;
-
- > printf ("Enter a number (0-9):\n");
- > scanf ("%d", &j);
-
- scanf() is not meant for processing raw data from a uncontrollable source,
- in this case, it's not a mortal sin, but it still isn't all that great. A
- better method would be to read a complete line into an appropriate buffer
- with fgets() (NOT gets()), and process it with either atoi(), or sscanf().
-
- Then, check to make sure the whole line fit in the buffer (i.e. was there a
- newline preceding the '\0' in the buffer), and possibly eat the remaining
- bit of the line with getchar() in a loop.
-
- > gets (dummy); /* *** Get the empty string *** */
-
- gets() doesn't check buffer sizes, to see a possibly spectacular failure,
- just enter "3<with a lot of giberish following the number>\n" at the prompt
- printed above. I'm not responsible if what you type happens to cause damage
- :-)
-
- > printf ("Enter 10 strings:\n");
- > for (i = 0; i < 10; i++) /* get 10 strings */
- > gets (str[i]);
-
- see comment above about gets(), however you must be aware that if one line
- was too long, the tail of it will be read on the next iteration. You have
- to handle a bit more when using fgets(), but it's much better than
- overwriting random parts of your program. This type of error wouldn't be
- caught in most memory protected systems, since the program is still
- accessing memory inside its address space (unless you type a truly excessive
- amount of gibberish).
-
- > if (j >= 0 && j < 10) /* *** changed *** */
- > printf ("Answer: %s\n", str[j]);
-
- > return 1;
-
- it would be more appropriate to return 0, (or EXIT_SUCCESS), instead of 1.
-
- >}
-